package com.prj.ufdm.demo.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HTTPS 工具
* @Description: TODO
* @date 2016年5月26日 
* @author 胡义振
 */
public class UfdmRequestHttps {

	private static Logger logger = LoggerFactory.getLogger(UfdmRequestHttps.class);
	
	public static void main(String [] arg) throws Exception{
		
		String url = "https://localhost:8443/test/doTest";
		//System.setProperty("javax.net.ssl.trustStore", "d:/key/tr_server_trust.jks" );
		System.out.println(postStream(url,"",null));
		
	}
	
	/**
	 * @Description: Https POST stream 请求
	 * @param svrUrl
	 * @param content
	 * @param encode
	 * @return
	 * @throws Exception
	 * 
	 * @date 2016年5月27日 
	 * @author 胡义振
	 */
	public static String postStream(String svrUrl, String content, String encode) throws Exception {

		if(encode==null || encode.equals("")){
			encode = "UTF-8";
		}
		String res = "";

		try
		{
			logger.info("\n 调用 JkRequestHttps  postStream -- Request Url:" + svrUrl + "  Request Param:"+content); 
			
			SSLContext sslContext = SSLContext.getInstance("SSL");
			TrustManager[] arrTrustManager = { new UfdmX509TrustManager() };
			sslContext.init(null, arrTrustManager, new java.security.SecureRandom());
			SSLSocketFactory ssfSocketFactory = sslContext.getSocketFactory();  
			
			URL console = new URL(svrUrl);
			HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
			conn.setSSLSocketFactory(ssfSocketFactory);
			conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
			conn.setDoOutput(true);
			conn.connect();
			DataOutputStream out = new DataOutputStream(conn.getOutputStream());
			out.write(content.getBytes(encode));
			// 刷新、关闭
			out.flush();
			out.close();
	
			// 读取返回数据
			StringBuffer strBuf = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuf.append(line);
			}
			res = strBuf.toString();
			reader.close();
			reader = null;
			
			logger.info("\n 调用 JkRequestHttps  postStream -- Request Result:" + res); 
		}
		catch(Exception er){
			logger.info("\n 调用 Request https  postStream 出现异常 -- Request Url:" + svrUrl + "  Request Param:"+content); 
			er.printStackTrace();
		}

		return res;
	}
	
	
	/**
	 * 描述: HTTPS POST 提交文件
	 * @auther 胡义振
	 * @param svrUrl  请求地址
	 * @param textMap 提交字段 
	 * @param fileMap 提交文件
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String postUpload(String svrUrl, Map<String, String> textMap,	Map<String, File> fileMap) {
		
		logger.info("\n 调用 JkRequestHttps  postUpload -- Request Url:" + svrUrl + "  Request Param textMap:"+fileMap + ",fileMap:"+fileMap); 
		
		String res = "";
		HttpsURLConnection conn = null;
		String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符
		try {
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, new TrustManager[] { new UfdmX509TrustManager() }, new java.security.SecureRandom());
			
			URL url = new URL(svrUrl);
			conn = (HttpsURLConnection) url.openConnection();
			conn.setSSLSocketFactory(sc.getSocketFactory());
			conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(30000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
			conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
			OutputStream out = new DataOutputStream(conn.getOutputStream());
			// 字段 
			if (textMap != null) {
				StringBuffer strBuf = new StringBuffer();
				Iterator iter = textMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
					strBuf.append("Content-Disposition: form-data; name=\""	+ inputName + "\"\r\n\r\n");
					strBuf.append(inputValue);
				}
				out.write(strBuf.toString().getBytes());
			}

			// 文件
			if (fileMap != null) {
				Iterator iter = fileMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					String inputName = (String) entry.getKey();
					
					File inputFile = (File) entry.getValue();
					
					String filename = inputFile.getName();
					
					StringBuffer strBuf = new StringBuffer();
					strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
					strBuf.append("Content-Disposition: form-data; name=\""	+ inputName + "\"; filename=\"" + filename	+ "\"\r\n");
					strBuf.append("Content-Type:application/octet-stream\r\n\r\n");

					out.write(strBuf.toString().getBytes());

					DataInputStream in = new DataInputStream(new FileInputStream(inputFile));
					int bytes = 0;
					byte[] bufferOut = new byte[1024];
					while ((bytes = in.read(bufferOut)) != -1) {
						out.write(bufferOut, 0, bytes);
					}
					in.close();
				}
			}

			byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
			out.write(endData);
			out.flush();
			out.close();

			// 读取返回数据
			StringBuffer strBuf = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuf.append(line).append("\n");
			}
			res = strBuf.toString();
			reader.close();
			reader = null;
			
			logger.info("\n 调用 JkRequestHttps  postUpload -- Request Result:" + res); 
			
		} catch (Exception e) {
			
			logger.info("\n 调用 Request postUpload 出现异常 -- Request Url:" + svrUrl + "  Request Param textMap:"+fileMap + ",fileMap:"+fileMap); 
			
			e.printStackTrace();
			
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
		return res;
	}
	
	private static class TrustAnyHostnameVerifier implements HostnameVerifier {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}

}